package org.thingsboard.server.transport.mqtt.util;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class MqttPublisher {
    private static final String BROKER_URL = "tcp://127.0.0.1:1884";
    private static final String CLIENT_ID = "rexkit-pub";
    private static final String USERNAME = "rexkit-pub";
    private static final String PASSWORD = "rexkit-pub";
    private static MqttClient instance;

    private MqttPublisher () {
    }
    /**
     * MQTT连接参数设置
     */
    private static MqttConnectOptions mqttConnectOptions(String clientId, String userName, String passWord) throws MqttException {
        instance = new MqttClient(BROKER_URL, clientId, new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        //用户名
        options.setUserName(userName);
//        MessageDigest md = MessageDigest.getInstance("SHA-256");
//        byte[] hashedPassword = md.digest((passWord).getBytes());
        //密码
        options.setPassword(passWord.toCharArray());
        //连接超时，默认：30
        options.setConnectionTimeout(30);
        //自动重新连接，默认：false
        options.setAutomaticReconnect(true);
        //清理会话，默认：true
        options.setCleanSession(false);
        //保持活动间隔，默认：60
        options.setKeepAliveInterval(60);
        return options;
    }

    public static MqttClient getInstance() {
        if (instance == null) {
            synchronized (MqttPublisher.class) {
                try {
                    MqttConnectOptions options = mqttConnectOptions(CLIENT_ID, USERNAME, PASSWORD);
                    instance.connect(options);
                } catch (MqttException e) {
                    log.error("MqttPublisher getInstance  connect failed", e);
                    throw new RuntimeException(e);
                }
            }
        }
        return instance;
    }

    public static void destroyInstance() {
        instance = null;
    }

    public static void publish(String topic, String payload) {
        try {
            MqttMessage message = new MqttMessage(payload.getBytes());
            // 发布消息
            MqttPublisher.getInstance().publish(topic, message);
            log.info("MqttPublisher publish success, topic:{}, payload:{}",topic, payload);
        }catch (MqttException e){
            log.error("MqttPublisher publish failed, payload:{}",payload, e);
        }
    }



    public static void main(String[] args) {
        // 创建MQTT客户端
        String payload = "{\"test\":\"1\"}";
        // 发布消息
//        MqttPublisher.publish(payload);
        MqttPublisher.destroyInstance();
    }
}
